using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Pricom.Controls
{
  public class HistoryTextBox : TextBox
  {
    public void SetLastHistory(string s)
    {
      if (inputHistory.Count == 0)
        inputHistory.Add(Text);
      historyIndex = inputHistory.Count - 1;
      inputHistory[historyIndex] = s;
    }

    public void AddHistory(string s)
    {
      inputHistory.Add(s);
      historyIndex = inputHistory.Count - 1;
    }

    protected void GoUpInHistory()
    {
      if (historyIndex == 0)
        return;
      if (historyIndex == inputHistory.Count - 1)
        SetLastHistory(Text);
      --historyIndex;
      string s = inputHistory[historyIndex];
      Text = s;
      SelectionStart = s.Length;
      SelectionLength = 0;
    }

    protected void GoDownInHistory()
    {
      if (historyIndex >= inputHistory.Count - 1)
        return;
      ++historyIndex;
      string s = inputHistory[historyIndex];
      Text = s;
      SelectionStart = s.Length;
      SelectionLength = 0;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
      Keys key = e.KeyCode;
      if (e.Modifiers == Keys.Control && key == Keys.V && LineEntered != null)
      {
        string paste = Clipboard.GetText();
        int linefeed = paste.IndexOf('\n');
        if (linefeed > -1 && linefeed < paste.Length - 1)
        {
          string[] lines = paste.Split('\n');
          foreach (string line in lines)
            if (line.Length > 0)
              LineEntered.Invoke(this, line);
          e.SuppressKeyPress = true;
          e.Handled = true;
        }
      }
      else if (key == Keys.Up)
      {
        GoUpInHistory();
        e.Handled = true;
      } 
      else if (key == Keys.Down)
      {
        GoDownInHistory();
        e.Handled = true;
      }
      if (!e.Handled)
        base.OnKeyDown(e);
    }

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
      if (e.KeyChar == (char)Keys.Enter)
      {
        if (Text.Length > 0)
        {
          SetLastHistory(Text);
          AddHistory("");
          LineEntered.Invoke(this, Text);
        }
        Clear();
        e.Handled = true;
      }
      else if (e.KeyChar == (char)Keys.Escape && EscapePressed != null)
      {
        EscapePressed.Invoke(this);
        e.Handled = true;
      }
      else
      {
        SetLastHistory(Text + e.KeyChar);
      }

      base.OnKeyPress(e);
    }

    public delegate void LineEnteredEventHandler(object sender, string line);
    public delegate void EscapePressedEventHandler(object sender);
    public event LineEnteredEventHandler LineEntered;
    public event EscapePressedEventHandler EscapePressed;
    private System.Collections.Generic.List<string> inputHistory = new System.Collections.Generic.List<string>();
    private int historyIndex = 0;
  }
}
